package com.nmgsr.ptmsapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.nmgsr.beans.requestdao.LoginReq;
import com.nmgsr.beans.responsedao.LoginRes;
import com.nmgsr.beans.service.Api;
import com.nmgsr.nettools.base.BaseActivity;
import com.nmgsr.nettools.net.config.NetManager;
import com.nmgsr.nettools.net.retrofit.BaseResponse;
import com.nmgsr.nettools.net.retrofit.HttpHelper;
import com.nmgsr.nettools.net.retrofit.HttpResponseObserver;
import com.nmgsr.nettools.net.retrofit.HttpUtil;
import com.nmgsr.nettools.util.ToastUtil;
import com.nmgsr.ptmsapp.R;
import com.nmgsr.ptmsapp.databinding.LoginActivityBinding;
import com.nmgsr.ptmsapp.utils.SM2Util;

import java.util.ArrayList;
import java.util.List;

public class LoginActivityBack extends BaseActivity {
    private LoginActivityBinding mBinding;
    private List<String> photoList = new ArrayList<>();
    @Override
    protected int getLayoutId() {
        return R.layout.login_activity1;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mBinding = LoginActivityBinding.inflate(getLayoutInflater());
        View view = mBinding.getRoot();
        setContentView(view);
        photoList.add("https://img1.baidu.com/it/u=51815545,3352787065&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500");
        photoList.add("https://img2.baidu.com/it/u=1633175549,4055880068&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=375");
        photoList.add("https://img.dlwjdh.com/upload/13105/210712/f06ae66511c7fd0b76544f732351a730.jpg");
        mBinding.getToken.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
//        mBinding.scanQrCode.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(LoginActivityBack.this, QRCodeScannerActivity.class);
//                startActivityForResult(intent, 1);
//            }
//        });
//        mBinding.toVideo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(LoginActivityBack.this, VideoActivity.class);
//                startActivity(intent);
//            }
//        });
//        mBinding.toImage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ImageActivity.startActivity(mContext, (ArrayList<String>) photoList, 0,false);
//            }
//        });
//
//        mBinding.toMaps.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(LoginActivityBack.this, MyMapEchartsActivity.class);
//                startActivity(intent);
//            }
//        });
//        mBinding.toUsb.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(LoginActivityBack.this, UsbReaderActivity.class);
//                startActivity(intent);
//            }
//        });
//        mBinding.takePhoto.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(LoginActivityBack.this, SingleCameraActivity.class);
//                startActivity(intent);
//            }
//        });
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                String qrCodeContent = data.getStringExtra("qrCodeContent");
                // 处理解析后的二维码内容
                handleQRCodeContent(qrCodeContent);
            }
        }
    }

    private void handleQRCodeContent(String qrCodeContent) {
        // 这里可以添加解析二维码内容的逻辑
        // 例如，解析设备信息并添加设备
        Toast.makeText(this, "扫描结果: " + qrCodeContent, Toast.LENGTH_LONG).show();
        // 假设二维码内容是一个设备ID
        String deviceId = qrCodeContent;
        // 添加设备的逻辑
        addDevice(deviceId);
    }

    private void addDevice(String deviceId) {
        // 实现添加设备的逻辑
        Toast.makeText(this, "设备添加成功: " + deviceId, Toast.LENGTH_LONG).show();
    }

    public void login() {
        String username = mBinding.username.getText().toString();
        String password = mBinding.password.getText().toString();
        if (!TextUtils.isEmpty(username)&&!TextUtils.isEmpty(password)){
            getToken();
        }else if (TextUtils.isEmpty(username)){
            ToastUtil.showToast("请输入用户名");
        }else if (TextUtils.isEmpty(password)){
            ToastUtil.showToast("请输入密码");
        }

    }

    private void getToken() {
        String original = "Hrjn@2025!";
        String encryptedHex = "";
        try {
            SM2Util.validateKeys();
            // 加密为C1C3C2格式HEX
            encryptedHex= SM2Util.encryptToC1C3C2Hex(original);
            Log.e("login", "C1C3C2 HEX密文: " + encryptedHex);
        } catch (Exception e) {
            Log.e("SM2Error", "加密失败", e);
            ToastUtil.showToast("安全模块错误：" + e.getMessage());
        }
        String username="superadmin";
        int tenantId = 0;
        int codeId = 0;
        String code = "string";
        LoginReq req = new LoginReq();
        req.setAccount(username);
        req.setPassword(encryptedHex);
        req.setTenantId(tenantId);
        req.setCodeId(codeId);
        req.setCode(code);
        showLoading("正在登录");
        HttpHelper.getInstance()
                .getService(Api.class)
                .userLogin(req)
                .compose(HttpUtil.defaultSchedulers())
                .compose(bindToLifecycle())
                .subscribe(new HttpResponseObserver<BaseResponse<LoginRes>>() {
                    @Override
                    protected void onSuccess(BaseResponse<LoginRes> response) {
                        dismissLoading();
                        String accessToken = response.getResult().getAccessToken();
                        Log.e("login", "onSuccess: " + accessToken);
                        String refreshToken = response.getResult().getRefreshToken();
                        NetManager.getInstance().appendHeader("Authorization", "Bear "+accessToken);
                        NetManager.getInstance().updateHeader();
                    }

                    @Override
                    protected void handleError(Throwable e) {
                        dismissLoading();
                        Log.e("e", "error: " + e.toString());

                    }
                });
    }
}
